// JRSwizzle.m semver:1.0
//   Copyright (c) 2007-2011 Jonathan 'Wolf' Rentzsch: http://rentzsch.com
//   Some rights reserved: http://opensource.org/licenses/MIT
//   https://github.com/rentzsch/jrswizzle

#import "Swizzle.h"

	#import <objc/runtime.h>
	#import <objc/message.h>


#define SetNSErrorFor(FUNC, ERROR_VAR, FORMAT,...)	\
	if (ERROR_VAR) {	\
		NSString *errStr = [NSString stringWithFormat:@"%s: " FORMAT,FUNC,##__VA_ARGS__]; \
		*ERROR_VAR = [NSError errorWithDomain:@"NSCocoaErrorDomain" \
										 code:-1	\
									 userInfo:[NSDictionary dictionaryWithObject:errStr forKey:NSLocalizedDescriptionKey]]; \
	}
#define SetNSError(ERROR_VAR, FORMAT,...) SetNSErrorFor(__func__, ERROR_VAR, FORMAT, ##__VA_ARGS__)

#define GetClass(obj)	object_getClass(obj)


@implementation NSObject (Swizzle)

+ (BOOL)swizzleMethod:(SEL)origSel_ withMethod:(SEL)altSel_ error:(NSError**)error_ {
    
    if(!(altSel_&&origSel_) ){
        
        return NO;
    };

    
    //为alloc后的类添加swizzle方法到方法列表中
     class_addMethod(self,
					altSel_,
					class_getMethodImplementation(self, altSel_),
					nil);
	
    Method origMethod = class_getInstanceMethod(self, origSel_);
    Method altMethod = class_getInstanceMethod(self, altSel_);
    
	method_exchangeImplementations(origMethod, altMethod);
    
 
	return YES;

}

+ (BOOL)swizzleClassMethod:(SEL)origSel_ withClassMethod:(SEL)altSel_ error:(NSError**)error_ {
	return [GetClass((id)self) swizzleMethod:origSel_ withMethod:altSel_ error:error_];
}

@end
